﻿using BootstrapBlazor.Components;
using Castle.Core.Logging;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using MPS.Entities;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc.UI.Theming;

namespace MPS.Blazor.Pages.Tables.MainTable
{
    public partial class MainTable : ComponentBase
    {
        [Inject]
        [NotNull]
        private IStringLocalizer<Foo>? Localizer { get; set; }

        [NotNull]
        private List<Foo>? Items { get; set; }
        private bool _confirm;
        private ConcurrentQueue<string> Message { get; } = new();

        private Alignment Align { get; set; }
        private AggregateType Aggregate { get; set; }
        /// <summary>
        /// 分页数据源
        /// </summary>
        private static IEnumerable<int> PageItemsSource => new int[] {10, 20, 30, 40 };
        /// <summary>
        /// 获得/设置 最大行数 默认 3 行
        /// </summary>
        [Parameter]
        public int Max { get; set; } = 3;

        [NotNull]
        private Modal? Modal { get; set; }
        private ToastService? toast { get; set; }

        private readonly ConcurrentDictionary<Foo, IEnumerable<SelectedItem>> _cache = new();

        private List<Foo> SelectedRows { get; set; } = [];

        private IEnumerable<SelectedItem> GetHobbys(Foo item)
        {
            return _cache.GetOrAdd(item, f => Foo.GenerateHobbys(Localizer));
        }

        [NotNull]
        private ConsoleLogger? Logger { get; set; }

        /// <summary>
        /// OnInitialized
        /// </summary>
        protected override void OnInitialized()
        {
            base.OnInitialized();
            //获取随机数据
            //Get random data
            Items = Foo.GenerateFoo(Localizer);
        }

        private Task<QueryData<Foo>> OnQueryAsync(QueryPageOptions options)
        {
            IEnumerable<Foo> items = Items;

            // 先处理过滤再处理排序 提高性能
            var isFiltered = false;
            if (options.Filters.Any())
            {
                items = items.Where(options.Filters.GetFilterFunc<Foo>());
                isFiltered = true;
            }

            // 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                items = items.Sort(options.SortName, options.SortOrder);
                isSorted = true;
            }

            // 设置记录总数
            var total = items.Count();

            // 内存分页
            items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

            return Task.FromResult(new QueryData<Foo>()
            {
                Items = items,
                TotalCount = total,
                IsSorted = isSorted,
                IsFiltered = isFiltered,
                IsSearch = true
            });
        }

        private Task OnDragColumnEndAsync(string? columnName, IEnumerable<ITableColumn> columns)
        {
            Message.Enqueue($"{DateTimeOffset.Now}: {$"Column: {columnName}"}");
            if (Message.Count > Max)
            {
                Message.TryDequeue(out _);
            }
            StateHasChanged();
            return Task.CompletedTask;
        }

        private async Task DownloadAsync(IEnumerable<Foo> items)
        {
            // Construct pop-up window configuration information and perform pop-up window operations
            var cate = ToastCategory.Information;
            var title = "Custom download example";
            var content = "Please select the data first, then click the download button";
            if (items.Any())
            {
                cate = ToastCategory.Success;
                content = $"start packing selected {items.Count()} data, this window will be closed automatically after completion";
            }

            var option = new ToastOption()
            {
                Category = cate,
                Title = title,
                Content = content,
            };
            // 弹出 Toast
            await toast.Show(option);
            // If the download item is selected for package download operation
            if (items.Any())
            {
                // Disable automatic shutdown
                option.IsAutoHide = false;
                // Start a background process for data processing
                // Passing Option used to be used to close the popup after the asynchronous operation
                await MockDownLoadAsync();
                // Close the popup associated with the option
                await option.Close();
                // A pop-up window informs that the download is complete
                await toast.Show(new ToastOption() { Category = ToastCategory.Success, Title = "Custom download example", Content = "data download complete", });
            }
        }

        private static async Task MockDownLoadAsync()
        {
            // It takes 5 seconds to simulate the package download data here
            await Task.Delay(5000);
        }

        private Task ShowDialog(IEnumerable<Foo> items)
        {
            return Modal.Toggle().AsTask();
        }

        private Task<QueryData<Foo>> OnQueryProductAsync(QueryPageOptions options)
        {
            var items = Items;

            var total = items.Count;
            // 内存分页
            items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

            return Task.FromResult(new QueryData<Foo>()
            {
                Items = items,
                TotalCount = total
            });
        }

        private async Task OnConfirm()
        {
            _confirm = true;
            await Modal.Toggle();
        }
    }    
}
